package ca.cbc.panacea.elixir.listener;

import ca.cbc.panacea.elixir.entity.PanaceaInstance;
import ca.cbc.panacea.elixir.exception.ElixirException;
import ca.cbc.panacea.elixir.persistence.EntityFacade;
import ca.cbc.panacea.elixir.service.PanaceaService;
import ca.cbc.panacea.elixir.util.PanaceaDaemon;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

/**
 * @author : Arash Bizhanzadeh <arash.bizhanzadeh@cbc.ca>
 *         Date: 11-12-07
 *         Time: 11:20 AM
 *         CBC.ca All rights reserved.
 */

public class ElixirContextListener implements ServletContextListener{
    private Logger logger = LoggerFactory.getLogger(ElixirContextListener.class);

    EntityFacade entityFacade = EntityFacade.instance;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        logger.info("Initializing the context ");
        logger.info("Service injection was successful ?: {}", entityFacade !=null);
        entityFacade.beginTransaction();
        List<PanaceaInstance> instances =  entityFacade.get().createQuery(" SELECT p from PanaceaInstance p ").getResultList();
        logger.debug("Instances had {} elements" , instances.size());
        try {
        for(PanaceaInstance instance : instances){
            if(!Strings.isNullOrEmpty(instance.getProcessId())){
                logger.info("Instance {} was running before shutdown. Start it", instance.getDirectory());
                String oldId = null;

                    oldId = PanaceaDaemon.probe(instance);

                if(Strings.isNullOrEmpty(oldId)){
                        PanaceaDaemon.start(instance);
                        instance.setProcessId(PanaceaDaemon.probe(instance));
                        logger.info("Instace {} started successfully.");
                    }
                    else{
                        logger.warn("Instance {} was already running, might be a bug in elixir.", instance.getDirectory());
                        instance.setProcessId(oldId);
                    }
                }
        }
               } catch (ElixirException e) {
                    logger.error("Error in initializing Elixir", e);
                }finally {
                entityFacade.commitTransaction();
        }

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        logger.info("Shutting down Elixir");
        entityFacade.beginTransaction();
        List<PanaceaInstance> instances =  entityFacade.get().createQuery(" SELECT p from PanaceaInstance p ").getResultList();
        logger.debug("Instances had {} elements" , instances.size());
        try {
        for(PanaceaInstance instance : instances){
            if(!Strings.isNullOrEmpty(instance.getProcessId())){
                logger.info("Instance {} is running Shutting down", instance.getDirectory());
                String oldId = null;
                PanaceaDaemon.stop(instance);
                oldId = PanaceaDaemon.probe(instance);
                if(Strings.isNullOrEmpty(oldId)){
                    logger.info("Instace {} started successfully.");
                }
            }
        }
               } catch (ElixirException e) {
                    logger.error("Error in initializing Elixir", e);
                }finally {
                entityFacade.commitTransaction();
        }
    }
}
